package com.youlin.untils;

import com.youlin.dto.res.SINameListResDto;
import com.youlin.dto.res.SINameResDto;
import com.youlin.entities.BygSignIn;
import net.sourceforge.pinyin4j.PinyinHelper;
import org.apache.commons.lang.StringUtils;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class PinYinSortUtil {

    public static List<SINameListResDto> pinYinSort (List<BygSignIn> signIns) {
        List<String> abc = Arrays.asList("QWERTYUIOPASDFGHJKLZXCVBNM".split(""));
        Map<Character, List<SINameResDto>> listMap = signIns.stream().map(signIn -> {
            String name = signIn.getName();
            String ret = "";
            for (char c : name.toCharArray()) ret += toPinYinString(c);
            if (! abc.contains(ret.split("")[0].toUpperCase())) ret = "#";
            return BaseService.copyProperties(signIn, SINameResDto.class).setSort(ret.toUpperCase());
        }).sorted(Comparator.comparing(SINameResDto::getSort))
            .collect(Collectors.groupingBy(signIn -> signIn.getSort().toCharArray()[0]));
        return listMap.keySet().parallelStream().sorted().map(k -> new SINameListResDto()
                .setAbc(k.toString().toUpperCase()).setNames(listMap.get(k))).collect(Collectors.toList());
    }

    public static String toPinYinString(char c) {
        String[] pyChars;
        try {
            pyChars = PinyinHelper.toHanyuPinyinStringArray(c);
            if(pyChars != null && pyChars.length >= 1){
                return pyChars[0].charAt(0)+"";
            }else if(StringUtils.isAlpha(c+"") || StringUtils.isNumeric(c+"")){
                return c+"";
            }else{
                return "";
            }
        } catch (Exception e) {
            return "";
        }
    }

}
